package com.jinrustar.httpfileserver.util;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.io.*;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

public class FileUtil {


    public static byte[] readFile(String filepath) throws IOException {
        FileChannel fileChannel = new FileInputStream(new File(filepath)).getChannel();
        long size = fileChannel.size();
        ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
        fileChannel.read(byteBuffer);

        /*var buffer = byteBuffer.flip()*/
        byte[] data = byteBuffer.array();
        System.arraycopy(data, 0, data, 0, (int) size);
        fileChannel.close();
        return data;
    }


    public static byte[] read(InputStream inputStream) throws IOException {
        byte[] bytes = new byte[1024];
        int len = 0;

        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        while (true) {
            len = inputStream.read(bytes, 0, bytes.length);
            if (-1 == len) {
                break;
            }
            baos.write(bytes, 0, len);
        }
        inputStream.close();
        return baos.toByteArray();
    }

    public static boolean exists(String path) {
        File f = new File(path);
        return f.exists();
    }


    @Data
    @AllArgsConstructor
    @NoArgsConstructor
    public static class FileInfo {
        private String name;
        private boolean isDir;
        private Long length;
        private long lastModifiedDate;
    }
}
